package com.tushen.utils;

import com.tushen.mapper.CommonDao;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * 数据源工具类
 * Created by likun on 2017/10/28.
 */
public class SqlSessionFactoryUtil {
    private static volatile SqlSessionFactory sqlSessionFactory;
    private static volatile SqlSessionFactory sqlOraclSessionFactory;

    public static SqlSessionFactory getSqlSessionFactory(){
        if(sqlSessionFactory==null){
            synchronized (SqlSessionFactory.class) {
                InputStream inputStream=null;
                try{
                    inputStream= Resources.getResourceAsStream("conf.xml");
                    sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
        return sqlSessionFactory;
    }


    public static SqlSession openSession(){
        return getSqlSessionFactory().openSession();
    }



    public static List<HashMap> excuteQuerySql(String sql){
        SqlSession sqlSession=null;
        try {
            sqlSession= SqlSessionFactoryUtil.getSqlSessionFactory().openSession();
            CommonDao commonDao=sqlSession.getMapper(CommonDao.class);
            List<HashMap> list=commonDao.executeSql(sql);
            sqlSession.close();
            return list;
        }catch (Exception e){
            e.printStackTrace();
            sqlSession.close();
        }
        return new ArrayList<HashMap>();
    }

    public static void excuteUpdateSql(String sql){
        SqlSession sqlSession=null;
        Connection connection=null;
        Statement statement=null;
        try {
            sqlSession= SqlSessionFactoryUtil.getSqlSessionFactory().openSession();
            connection=sqlSession.getConnection();
            statement=connection.createStatement();
            statement.execute(sql);
            statement.close();
            connection.commit();
            connection.close();
            sqlSession.close();
        }catch (Exception e){
            e.printStackTrace();
            sqlSession.close();
        }
    }
    static int trackCount=0;

    // 将数据入库
    public  static Connection dbConn;

    public static void dumpPGDatalist(ArrayList<HashMap> ls, String tableName)  throws Exception {
        System.out.println(tableName+" begin import " + (++trackCount) + " times,size:" + ls.size());

        if(dbConn==null) {
            dbConn = SqlSessionFactoryUtil.getSqlSessionFactory().openSession().getConnection();
        }
            StringBuilder sb2=new StringBuilder();
            StringBuilder sb=new StringBuilder();
            sb.append("insert into "+tableName+" (");
            if(ls.size()==0)return;
            HashMap map1=(HashMap) ls.get(0);
            for (Object key:map1.keySet()){
                sb.append(key.toString()+",");
                sb2.append("?,");
            }
            sb2.deleteCharAt(sb2.lastIndexOf(","));
            sb.deleteCharAt(sb.lastIndexOf(","));
            sb.append(") values(");
            sb.append(sb2.toString()+") on CONFLICT do NOTHING");
            PreparedStatement psta = dbConn.prepareStatement(sb.toString());
            psta.clearBatch();
            Iterator<HashMap> it = ls.iterator();
            while (it.hasNext()) {
                HashMap tr = it.next();
                int index=1;
                for (Object key:tr.keySet()){
                    psta.setObject(index++,tr.get(key));
                }
                psta.addBatch();
            }
            psta.executeBatch();
            dbConn.commit();
            psta.close();
            System.out.println(" import " + (trackCount) + " times finish");

    }
    public static void dumpDatalist2(ArrayList<HashMap> ls, String tableName)  {
        System.out.println("插入记录 " + (++trackCount) + "次,数据量：" + ls.size());

        if(dbConn==null) {
            dbConn = SqlSessionFactoryUtil.getSqlSessionFactory().openSession().getConnection();
        }
        try {
            StringBuilder sb2=new StringBuilder();
            StringBuilder sb=new StringBuilder();
            if(ls.size()==0)return;


            Iterator<HashMap> it = ls.iterator();
            while (it.hasNext()) {
                HashMap tr = it.next();
                sb.append("insert into ");
                sb.append(tableName);
                sb.append("(");
                for (Object key:tr.keySet()){
                    sb.append(key.toString()+",");
                    if(tr.get(key) instanceof String){
                        sb2.append("'"+tr.get(key)+"',");
                    }else {
                        sb2.append(tr.get(key)+",");
                    }

                }
                sb.deleteCharAt(sb.length()-1);
                sb2.deleteCharAt(sb2.length()-1);
                sb.append(") values(");
                sb.append(sb2.toString()+");");
                sb2=new StringBuilder();
            }
            Statement psta = dbConn.createStatement();
//            System.out.println(sb.toString());
            psta.executeUpdate(sb.toString());
            dbConn.commit();
            psta.close();
            System.out.println("插入" + (trackCount) + "次完成");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.print("连接失败");
        }
    }
}
